using System;
using System.Data;
using System.Text;
using System.Windows.Forms;

using FreeFlow.Client;

namespace FreeFlow.WinFormsControls
{
	/// <summary>
	/// A grid control.
	/// </summary>
	public class GridControl : DataGridView, IFillable
	{
    /// <summary>
    /// Creates a new <see cref="GridControl"/> instance.
    /// </summary>
		public GridControl()
		{
      RowHeadersVisible = false;
    }

    #region IFillable Members

    /// <summary>
    /// Renders the grid with static layout information using the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Render(FreeFlow.Client.Field field)
    {
      GridField gridField = field as GridField;

      AllowUserToAddRows = gridField.GridType == GridType.Edit;
      AllowUserToDeleteRows = gridField.GridType == GridType.Edit;

      for (int i = 0; i < gridField.ColumnCount; i++)
      {
        GridColumn col = gridField.Column(i);
        int index = Columns.Add(col.Caption, col.Caption);
        Columns[index].Width = col.Width;
        Columns[index].Visible = col.Usage != FieldUsage.Hidden;
      }  
    }

    /// <summary>
    /// Fills the grid with values from the specified field.
    /// </summary>
    /// <param name="field">Field.</param>
    public void Fill(FreeFlow.Client.Field field)
    {
      GridField gridField = field as GridField;
      DataSource = gridField.Data;
      if (gridField.Data != null)
      {
        for (int i = 0; i < gridField.ColumnCount; i++)
        {
          if (gridField.Data.Columns.Count > i)
            Columns[i].DataPropertyName = gridField.Data.Columns[i].ColumnName;
        }
      }
    }

    /// <summary>
    /// Fills the field from the control.
    /// </summary>
    /// <param name="field">Field.</param>
    public void FillField(Field field)
    {
      if (field != null)
      {
        DataRowView selectedRow = SelectedRow;

        StringBuilder builder = new StringBuilder();
        GridField gridField = (GridField)field;
        if (gridField.Data != null)
        {
          for (int i = 0; i < gridField.Data.Columns.Count; i++)
          {
            builder.Append(selectedRow[i].ToString() + "\t");
          }
          field.Value = builder.ToString();
        }
      }
    }

    #endregion

    /// <summary>
    /// Gets the selected row.
    /// </summary>
    public DataRowView SelectedRow
    {
      get
      {
        if (DataSource != null)
        {
          BindingManagerBase bm = BindingContext[DataSource];
          return (DataRowView)bm.Current;
        }

        return null;
      }
    }
  }
}
